package com.lafer.xiao.service;

import com.lafer.xiao.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class ExcelService {
    public void export(HttpServletResponse response) {
        //此处写固定数据，一般数据都是查数据库获取
        String sheetName = "学生成绩表";
        List<String> title = new ArrayList<>(){{
            add("姓名"); add("数学"); add("语文"); add("英语"); add("物理"); add("化学");
        }};
        List<String> nameList = new ArrayList<>(){{
            add("张三"); add("李四"); add("王五"); add("赵六"); add("卓七"); add("鹰八");
        }};
        Random random = new Random();
        List<List<Object>>content = new ArrayList<>();
        nameList.forEach(name->{
            List<Object> dataList = new ArrayList<>(){{
                add(name); add(random.nextInt(100)); add(random.nextInt(100)); add(random.nextInt(100)); add(random.nextInt(100)); add(random.nextInt(100));
            }};
            content.add(dataList);
        });

        //创建excel
        HSSFWorkbook wb = ExcelUtil.exportSimpleExcel(sheetName, title, content);

        //输出Excel文件
        try {
            OutputStream output = response.getOutputStream();
            response.reset();
            //获取当前时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            //filename 文件名称
            response.setHeader("Content-disposition", "attachment; filename="+df.format(new Date())+".xls");
            wb.write(output);
            output.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
